const path = require("path");
const Help = require("./help.js");
const fs = require("fs");
async function  main(){
  global["json_exe_dir"]=path.dirname(process.argv[0]) //正式运行的路径
  global["json_last_msg"]=""
  if(process.env.debugENV === 'debug'){
    global["json_exe_dir"]=path.dirname(process.argv[1])//调试用的路径
  }
  if(!global["json_config"]){
    global["json_config"]=require("./config.js");   
  }
  if(!global["class_rabbitmq"]){
    await Help.Init_RabbitMQ()
  }
  if(!global["Mongo_Connection"]){
    await Help.Init_Mongo()
  }
  if(!global["class_s3"]){
    await Help.Init_S3()
  }
  global["user_gistack_token"]="eyJraWQiOiJrMSIsImFsZyI6IlJTMjU2In0.eyJpc3MiOiJhZG1pbkBnaXN1bmkuY29tIiwiYXVkIjoidXVtcyIsImV4cCI6MTcyNTc2MjQ5MywianRpIjoiUWFjR0N3dG5hN3AyV3pyQlBLUXRPQSIsImlhdCI6MTcyNTE1NzY5MywibmJmIjoxNzI1MTU3MzkzLCJzdWIiOiJzdXBlciIsImlkIjoic3VwZXIiLCJuYW1lIjoic3VwZXIiLCJ0eXBlIjoiMiIsImNsaWVudGlkIjpudWxsLCJmcm9tIjoidXVtcyIsImV4cGlyZXMiOiIxNzI1NzYyNDkzMjM2Iiwicm9sZXMiOlsiY29tbW9uX2NoYW5nZV9kZXRlY3Rpb24iLCJkYXRhX21hbmFnZXIiLCJ0ZHNwX21hbmFnZXIiLCJzaHBjaGVja19hZG1pbiIsImNyb3BfbW9kZWxfbWFuYWdlciIsImFsdGhtX21hbmFnZXIiLCJkZGNnIiwiY29tbW9uX2NoYW5nZV9hZG1pbiIsImR5X21hbmFnZXIiXX0.OZYQPYWX0T8v1E9PFlPJA2xRkw96HKF53tuUJGiLp4dPIA8uYo1T6ANlSI5BClNQujRrn1I0C0y5-XcOWF8eBkfxwdBVp3JoLln5-0ZgvGrXvPBxAYwbCFdFmAKsLtOUWGX7dOLW70lRXUVAFWiGYrhspQuTlRLEj_WPXrBKdRGgvGSoojdASk0I9qjKbZvEWHwFkk9EZSlzTrCdn-Kdu3u07UbSpRU9PLx4kXJGhFsvrMhs9o6lmIs40cpBbmOMUw9GRJvuEod5SF87ROa_1LExMwEkoixyOElHdaMO1QVrVZjogMepbQjbpzU9JtjDWUyFQDGFkKB4r9siHlXgGQ"
  let login_status=await init_login();
  if(login_status==false){
    Help.Console_log("登录uums失败")
    return false
  }
  setInterval (async ()=>{
    login_status=await init_login();
  },1000*60*30*1) 
  Help.add_download_process();
  
  await init_server();
  Help.Console_log("start ...")
  if(global["class_rabbitmq"]){
    await Help.wait_tif_move_to_done_dir()
    await Help.wait_rabbitmq_done_2work()
    // await  Help.Search_L1_Tasks()

    // await Help.Search_L1_Tasks_other()
    // await Help.down_zy3()
  }
}
async function  init_login(){
  let login_status=false
  // Help.Console_log("start_update user_gistack_token")
  login_status=await Help.init_login();
  // Help.Console_log(`update user_gistack_token end ${login_status}`)
  // Help.Console_log(`new user_gistack_token is ${global["user_gistack_token"]}`)
  return login_status
}
async function  add_task_to_mq(){
  let data=[
    {
      batch:'202410210048520',
      orderid:'bwszx',
      username:'bwxzx',
    },
    {
      batch:'202410220050530',
      orderid:'bwszx',
      username:'bwxzx',
    }
  ]
  for (let i = 0; i < data?.length; i++) {
    let one_data = data[i];
    await Help.add_rabbitmq(one_data,"sdp_pri");
    
  }
  return true
}
async function  init_server(){
  const http = require('http');
  const Koa = require("koa"); 
  const bodyparser = require("koa-bodyparser");
  const json = require("koa-json");
  const static = require('koa-static');
  const { historyApiFallback } =require('koa2-connect-history-api-fallback');
  const app = new Koa();
  return new Promise((resolve)=>{
    app.use(async (ctx, next) => {
      ctx.set("Access-Control-Allow-Origin", "*")
      ctx.set("Access-Control-Allow-Methods","POST, GET");
      ctx.set("Access-Control-Allow-Headers","x-requested-with,authorization,Content-Type,Accept,client,Aworker");
      if (ctx.request.method == "OPTIONS") {ctx.response.status = 200;}
      else {
        try {await next();} 
        catch (err) {
          ctx.response.status = err.statusCode || err.status || 500;
          ctx.response.body = {message: err.message}
        }
      }
    });
    //获取post传过来的参数
    app.use(bodyparser({
      enableTypes: ["json", "form", "text"],
      encoding:'utf-8', //限制上传的数据量
      formLimit:'50mb',
      jsonLimit:'50mb',
      textLimit:'50mb',
      strict:true,
      detectJSON:null,
      multipart: true,
      extendTypes:{
        json: ['application/x-javascript'], 
      },
      onerror:function (err, ctx) {
        ctx.throw('body parse error', 422);
      }
    }));
    app.use(json());
    app.use(historyApiFallback({ 
      whiteList: ['/task'],
      index: '/index.html'
    }));
    app.use(static(`${global["json_exe_dir"]}/html`)); 
    const router_wmts_con= require("./www/wmts_con.js")
    app.use(router_wmts_con.routes(), router_wmts_con.allowedMethods());
    const server= http.createServer(app.callback());
    server.on("error", async (error)=> {
      Help.Console_log(`创建服务器失败:${error.message}`)
      resolve(false)
    });
    server.on("listening", async()=> {
      let addr = server.address();
      Help.Console_log(`http://127.0.0.1:${addr.port}`)
      resolve(true)
    });
    server.listen(global["json_config"]?.port);
  })
}
main().then(()=>{

})